import 'dart:convert';

import '../bean/favourites.dart';
import '../util/shared_preferences_util.dart';

/// 我喜欢的
class FavouritesRepository {
  static const String _keyFavourites = "key_favourites";

  /// 是否我喜欢的
  static Future<bool> isFavourite(String url) async {
    var favourites = await _getFavourites();
    for (var i = 0; i < favourites.length; i++) {
      Favourite bean = favourites[i];
      if (bean.url == url) {
        return Future.sync(() => true);
      }
    }
    return Future.sync(() => false);
  }

  /// 添加到我喜欢的
  static Future<bool> addFavourite(String url, String title) async {
    var favourites = await _getFavourites();
    for (var i = 0; i < favourites.length; i++) {
      Favourite bean = favourites[i];
      if (bean.url == url) {
        return Future.sync(() => true);
      }
    }
    Favourite favourite = Favourite(url, title);
    favourites.add(favourite);
    return await SharedPreferencesUtil.savePreference(
        _keyFavourites, jsonEncode(favourites));
  }

  /// 从我喜欢的中移除
  static Future<bool> removeFavourite(String url) async {
    var favourites = await _getFavourites();
    Favourite? targetBean;
    for (var i = 0; i < favourites.length; i++) {
      Favourite bean = favourites[i];
      if (bean.url == url) {
        targetBean = bean;
      }
    }
    if (targetBean == null) {
      return Future.sync(() => false);
    }
    var isSuccess = favourites.remove(targetBean);
    if (isSuccess) {
      return SharedPreferencesUtil.savePreference(
          _keyFavourites, jsonEncode(favourites));
    } else {
      return Future.sync(() => false);
    }
  }

  /// 获取所有我喜欢的
  static Future<List<Favourite>> getAllFavourite() async {
    return _getFavourites()
        //反转列表，新加的在上面
        .then((list) => list.reversed.toList());
  }

  static Future<List<Favourite>> _getFavourites() async {
    String favouritesJson =
        await SharedPreferencesUtil.getPreference(_keyFavourites, "") ?? "";
    List<Favourite> favourites;
    //有数据，则json解析为模型
    if (favouritesJson.isNotEmpty) {
      List<dynamic> list = json.decode(favouritesJson);
      favourites = list.map((e) => Favourite.fromJson(e)).toList();
    } else {
      //没有数据，则返回空列表
      favourites = <Favourite>[];
    }
    return favourites;
  }
}
